<template>
	<view class="container">

		<uni-segmented-control :current="currentIndex" :values="items" style-type="text" active-color="#007aff"
			@clickItem="onClickItem" />

		<view v-if="currentIndex === 0">
			<view style="padding-top: 10px;"></view>
			<view class="tips">
				填写说明：<br>
				1、请假1天需要部门领导审批，请假2天及以上需要分管领导审批，科室负责人请假1天或需要离开盐城都需要主要领导审批。<br>
				2、递交请假单需要上传相关证明，请拍照上传。如三甲医院病假条
			</view>
			<uni-forms ref="baseForm" :modelValue="vacationApplyForm" labelPosition="left" :border="true"
				labelWidth="100px">
				<view style="padding-top: 10px;"></view>

				<uni-forms-item label="申请人">
					<view class="text-bg">{{userName}}</view>
				</uni-forms-item>
				<uni-forms-item label="请假类型" required>
					<view class="checkbox-bg">
						<uni-data-checkbox v-model="vacationApplyForm.leixing" :localdata="typeStrs" @change="qingjiaTypChange" />
					</view>
				</uni-forms-item>
				<uni-forms-item label="开始时间" required>
					<uni-datetime-picker @click="chuanci()" @change="dateChangeStart" @maskClick="chuanci2()" type="datetime" :start="startDate"
						return-type="string" v-model="vacationApplyForm.startDate" />
				</uni-forms-item>
				<uni-forms-item label="结束时间" required>
					<uni-datetime-picker @click="chuanci()" @change="dateChangeEnd" @maskClick="chuanci2()" type="datetime" :start="startDate"
						return-type="string" v-model="vacationApplyForm.endDate" />
				</uni-forms-item>
				<uni-forms-item label="请假时长">
					<view class="text-bg">{{qingjiaDaysStr()}}</view>
					<!-- <uni-easyinput :inputBorder="false" :placeholder="qingjiaDaysStr()" disabled></uni-easyinput> -->
				</uni-forms-item>
				<uni-forms-item label="请假事由" required>
					<uni-easyinput type="textarea" @change="chuanci2" @input="chuanci2" autoHeight
						v-model="vacationApplyForm.reason" />
				</uni-forms-item>
				<uni-forms-item label="是否出盐城" required>
					<view class="checkbox-bg">
					<uni-data-checkbox v-model="vacationApplyForm.outYancheng" :localdata="outYanchengStrs" @change="yanchengChange" />
					</view>
				</uni-forms-item>

				<!-- 附件模块 -->
				<uni-forms-item label="附件"></uni-forms-item>
				<view v-for="(item,index) in files.values()" :key="index">
					<view v-if="item.type=='success' && item.size <=1048576">[{{(item.size/1024).toFixed(2)}}KB]
						{{item.name.substring(0,30)}}

					</view>
					<view v-if="item.type=='success' && item.size >1048576">[{{(item.size/1048576).toFixed(2)}}MB]
						{{item.name.substring(0,30)}}

					</view>
					<view v-if="item.type!='success'"><i style="color: royalblue;">上传{{item.progress}}%</i>
						{{item.name.substring(0,30)}}</view>
				</view>
				<lsj-upload ref="lsjUpload" childId="upload1" height="40px" :size="uploadconfig.size"
					:instantly="uploadconfig.instantly" :formats='uploadconfig.formats' :option="option"
					@change="onChange" @progress="onprogress" @uploadEnd="onuploadEnd">
					<button class="btn-fujian" @click="fuckyou">添加附件</button>

				</lsj-upload>
				<view class="tips">说明：从此上传图片将无法预览，单个文件请控制在100MB以内</view>

				<!-- 图片上传模块 -->
				<uni-forms-item label="相关证明"></uni-forms-item>
				<uni-row>
					<uni-col :span="8" v-for="(item, idx) in vacationApplyForm.pics" :key="idx">
						<view class="img-res" @click="showBigImg(vacationApplyForm.pics,idx)">
							<image :src="vacationApplyForm.pics[idx]" :key="idx" />
						</view>
					</uni-col>
				</uni-row>
				<button @click="clickSelectPic" class="btn-add">选择图片</button>

				<!-- 选人模块 -->
				<uni-forms-item label="审核人" required></uni-forms-item>
				<view v-for="(item, idx) in vacationApplyForm.auditors" :key="idx">
					<uni-row>
						<uni-col :span="10">
							<view v-if="idx>0" class="step-arrow">
								<uni-icons type="bottom" size="mini" color='#a5eaff'></uni-icons>
							</view>
						</uni-col>
					</uni-row>

					<view class="step">
						<uni-row>
							<uni-col :span="10">
								<view class="step-info-left">{{item.stepName || item.positionName}}</view>
							</uni-col>
							<uni-col :span="14">
								<view class="step-info-right">{{item.name}}</view>
							</uni-col>
						</uni-row>
					</view>
				</view>

				<view style="padding-top: 30px;"></view>
				<button type="primary" @click="clickApply">提交</button>
			</uni-forms>
		</view>

		<view v-if="currentIndex === 1">
			<view v-for="(item, idx) in applyRecord" style="padding-bottom: 10px;" :key="idx">
				<view class="card" @click="seeDetail(idx)">
					<view class="card-title">
						<uni-row>
							<uni-col :span="20">
								<view class="card-title-left">{{item.leixing}}</view>
							</uni-col>
							<uni-col :span="4">
								<view class="card-title-right">
									<uni-tag text="审核" size="mini" type="warning" v-if="item.sta===0&&item.chexiao==0"></uni-tag>
									<uni-tag text="通过" size="mini" type="primary" v-if="item.sta===1&&item.chexiao==0"></uni-tag>
									<uni-tag text="拒绝" size="mini" type="error" v-if="item.sta===2&&item.chexiao==0"></uni-tag>
									<uni-tag text="撤销" size="mini" type="default" v-if="item.chexiao===1"></uni-tag>
								</view>
							</uni-col>
						</uni-row>
					</view>
					<view class="card-body">
						<view>开始时间：{{item.startDate}}</view>
						<view>结束时间：{{item.endDate}}</view>
						<view>小时数：{{item.days}}</view>
					</view>
					<view class="card-footer">
						<uni-row>
							<uni-col :span="24">
								<view class="card-footer-right">
									{{getFormatedTimeStr(item.createTime)}}
								</view>
							</uni-col>
						</uni-row>
					</view>
				</view>
			</view>

			<uni-load-more :status="moreStatus"></uni-load-more>
		</view>
	</view>
</template>

<script>
	import moment from 'moment'
	import {
		websock
	} from '../../net/websock'
	import store from '../../store'
	import {
		uploadconfig
	} from '../../const'
	import { quchongAuditors } from '../../utils/util'

	export default {
		data() {
			return {
				// 上传参数部分没有事情不要乱动
				uploadconfig,
				option: {
					url: uploadconfig.url,
					name: 'file',
					header: {},
					formData: {}
				},
				formats: uploadconfig.formats,
				instantly: uploadconfig.instantly,
				size: uploadconfig.size,
				files: new Map(),
				// 上传参数部分没有事情不要乱动

				userInfo: {},
				typeStrs: [],
				timeTypeLabel: '请假天数',
				outYanchengStrs: [{
					text: "否",
					value: '否'
				}, {
					text: "是",
					value: '是'
				}],
				moreStatus: 'more',
				userName: '',

				currentIndex: 0,
				items: ['发起提交', '查看数据'],
				applyRecord: [],
				uppers: [],
				auditors: [], // 审核人
				lingdao: {}, // 领导
				qingjiaDetail: [], // 请假详情
				vacationApplyForm: {
					leixing: '',
					startDate: '',
					endDate: '',
					days: 0,
					outYancheng: '否',
					reason: '',
					auditors: [],
					attaches: [],
					pics: []
				},
				startDate: ''
			}
		},
		async onReady() {
			try {
				this.userInfo = await websock.getUserInfo()
				this.userName = this.userInfo.name
				console.log('user info', this.userInfo)

				// 获取请假类别的配置
				let qingjiaList = await websock.qingjiaList()
				for (let i = 0; i != qingjiaList.length; i++) {
					this.typeStrs.push({
						text: qingjiaList[i].name,
						value: qingjiaList[i].name
					})
				}

				this.auditors = await websock.getAuditors({typ: 0})
				console.log('auditors', this.auditors)
				quchongAuditors(this.auditors)
				// this.vacationApplyForm.auditors = this.auditors.slice()
				this.checkAuditors()

				this.lingdao = await websock.getLingdao()
				console.log('my lingdao info', this.lingdao)

				this.getNewestRecord()
				console.log('qingjia on ready apply record', this.applyRecord)

				this.startDate = moment().format('YYYY-MM-DD')
			} catch (e) {
				uni.showToast({ title: e.message })
			}
		},
		// 下拉刷新，获取最新的数据
		onPullDownRefresh() {
			console.log('onPullDownRefresh')
			if (this.currentIndex == 0) {
				uni.stopPullDownRefresh()
			} else {
				this.getNewestRecord()
			}
		},
		// 上拉刷新，获取历史数据
		onReachBottom() {
			console.log('onReachBottom')
			if (this.currentIndex == 1) {
				this.getOlderRecord()
			}
		},
		methods: {
			// 附件上传恶心的代码块
			// 某文件上传结束回调(成功失败都回调)
			onuploadEnd(item) {
				console.log('fuck you', 3)
				if (item.type == 'fail') {
					return uni.showToast({
						title: '上传失败'
					})
				}
				try {
					let res = JSON.parse(item.responseText)
					if (res.code !== 0) {
						return uni.showToast({
							title: res.message || 'error'
						})
					}
					this.vacationApplyForm.attaches.push({
						name: item.name,
						path: res.data
					})
				} catch (err) {
					uni.showToast({
						title: err.message
					})
				}
				this.$forceUpdate();
			},
			// 上传进度回调
			onprogress(item) {
				this.files.set(item.name, item); // 更新当前状态变化的文件
				this.$forceUpdate(); // 强制更新视图
			},
			// 文件选择回调
			onChange(files) {
				this.files = files; // 更新选择的文件 
				this.$forceUpdate(); // 强制更新视图
			},
			// 穿刺一击让他们的遮罩层消失
			chuanci() {
				this.$refs.lsjUpload && this.$refs.lsjUpload.hide();
			},
			// 穿刺一击让他们的遮罩层消失
			chuanci2() {
				this.$refs.lsjUpload && this.$refs.lsjUpload.show();
				this.$forceUpdate()
			},
			// 强制重置附件按钮,万一出意外点2次按钮至少可以进去
			fuckyou() {
				this.$forceUpdate()
				this.$refs.lsjUpload && this.$refs.lsjUpload.hide()
				this.$refs.lsjUpload && this.$refs.lsjUpload.show()

			},
			// 选择图片
			clickSelectPic() {
				uni.chooseImage({
					count: 9, //选择图片数
					sourceType: ['camera', 'album'], //从相册还是相机选择
					success: (res) => {
						for (let path in res.tempFilePaths) {
							uni.uploadFile({
								url: this.uploadconfig.url,
								filePath: res.tempFilePaths[path],
								name: 'file',
								formData: {
									uid: this.userInfo.uid,
									token: store.token
								},
								success: res => {
									try {
										let data = JSON.parse(res.data)
										if (data.code != 0) {
											return uni.showToast({
												title: data.message
											})
										}
										this.vacationApplyForm.pics.push(data.data)
									} catch (e) {
										console.error(e)
										uni.showToast({
											title: '上传图片失败' + e.message
										})
									}
									console.log('success', res)
								},
								fail: (res) => {
									uni.showToast({
										title: '上传图片失败' + res
									})
								},
								complete: () => {
									console.log('uploa file complete')
								}
							})
						}
					}
				})
			},
			//点击放大图片
			showBigImg(imgurl, cur) {
				uni.previewImage({
					current: cur,
					loop: true,
					urls: imgurl,
				})
			},

			// 显示选择器
			showPicker() {
				this.$refs.treePicker._show();
			},
			//监听选择（ids为数组）
			selectChange(ids, names) {
				console.log(ids, names)
			},
			// 获取最新的通知
			async getNewestRecord() {
				try {
					if (this.applyRecord.length == 0) {
						let res = await websock.vacationApplyRecord({
							pageCount: 10
						})
						console.log('getRecordList list empty', res)
						uni.stopPullDownRefresh()
						this.applyRecord = [...res, ...this.applyRecord]
					} else {
						let res = await websock.vacationApplyRecord({
							greaterThan: this.applyRecord[0].id,
							pageCount: 10
						})
						console.log('getRecordList list not empty', res)
						uni.stopPullDownRefresh()
						this.applyRecord = [...res, ...this.applyRecord]
					}
				} catch (e) {
					uni.showToast({
						title: e.message
					})
				}
			},
			// 获取格式化时间字符串
			getFormatedTimeStr(stamp, str='MM-DD HH:mm:ss') {
				return moment(stamp).format(str)
			},
			// 获取老的数据
			async getOlderRecord() {
				this.moreStatus = 'loading'
				try {
					if (this.applyRecord.length == 0) {
						let res = await websock.vacationApplyRecord({
							pageCount: 10
						})
						this.applyRecord = [...this.applyRecord, ...res]
						if (res.length < 10) {
							this.moreStatus = 'noMore'
						} else {
							this.moreStatus = 'more'
						}
					} else {
						let res = await websock.vacationApplyRecord({
							lessThan: this.applyRecord[this.applyRecord.length - 1].id,
							pageCount: 10
						})
						this.applyRecord = [...this.applyRecord, ...res]
						if (res.length < 10) {
							this.moreStatus = 'noMore'
						} else {
							this.moreStatus = 'more'
						}
					}
				} catch (e) {
					uni.showToast({
						title: e.message
					})
				}
			},
			onClickItem(e) {
				if (this.currentIndex !== e.currentIndex) {
					this.currentIndex = e.currentIndex
				}
			},
			qingjiaTypChange(e) {
				this.vacationApplyForm.leixing = e.detail.value
				console.log('qingjia typ change', this.vacationApplyForm.leixing, e)

				this.dateChange()
			},
			qingjiaDaysStr() {

				let hours = 0
				let diff = 0
				for (let i = 0; i != this.qingjiaDetail.length; i++) {
					let detail = this.qingjiaDetail[i]
					if (moment(detail.start).isAfter(moment(detail.end))) continue
					diff += (moment(detail.end).valueOf() - moment(detail.start).valueOf())
				}

				hours = Math.ceil(diff / 1000 / 60 / 60)

				if (this.vacationApplyForm.leixing == '因公外出') {
					return hours + ' 小时'
				} else {
					return Math.ceil(hours / 8) + ' 天'
				}
			},
			dateChangeStart(e) {
				console.log('date change start', e)
				this.vacationApplyForm.startDate = moment(e.trim()).format('YYYY-MM-DD HH:mm:ss')
				this.dateChange()
			},
			dateChangeEnd(e) {
				console.log('date change end', e)
				this.vacationApplyForm.endDate = moment(e.trim()).format('YYYY-MM-DD HH:mm:ss')
				this.dateChange()
			},
			yanchengChange() {
				this.checkAuditors()
			},
			async dateChange() {
				this.chuanci2()

				console.log('date change start', this.vacationApplyForm.startDate)
				console.log('date change end', this.vacationApplyForm.endDate)
				console.log('date change', this.vacationApplyForm.leixing)

				if (this.vacationApplyForm.startDate && this.vacationApplyForm.endDate) {
					let startTime = this.vacationApplyForm.startDate.trim()
					let endTime = this.vacationApplyForm.endDate.trim()
					if (this.vacationApplyForm.leixing != '因公外出') {
						startTime = moment(startTime).startOf('day').format('YYYY-MM-DD 09:00:00')
						endTime = moment(endTime).endOf('day').format('YYYY-MM-DD 17:00:00')
					}
					console.log('start time1111', startTime)
					console.log('end time11111', endTime)

					// 是否带上周末
					let zhoumo = 1
					// 是否带上节假日
					let jiejiari = 1

					// 产假不带上节假日
					if (this.vacationApplyForm.leixing == '产假') {
						jiejiari = 0
					}
					// 带薪休假不上周末和节假日
					if (this.vacationApplyForm.leixing == '带薪休假') {
						zhoumo = 0
						jiejiari = 0
					}
					this.qingjiaDetail = await websock.getShangbanDetail({startTime, endTime, zhoumo, jiejiari})
					console.log('date change shagnban detail', this.qingjiaDetail)
				}

				this.checkAuditors()
			},
			addAuditor(info) {
				if (!info.uid) return
				for (let i = 0; i != this.vacationApplyForm.auditors.length; i++) {
					if (this.vacationApplyForm.auditors[i].uid == info.uid) return
				}

				this.vacationApplyForm.auditors.push(info)
			},
			checkAuditors() {

				// 塞一个默认审核人
				this.vacationApplyForm.auditors = []
				let defaultAuditors = this.auditors.slice()
				console.log('default auditors', defaultAuditors)
				for (let i = 0; i != defaultAuditors.length; i++) {
					if (defaultAuditors[i].sta == '0') {
						this.vacationApplyForm.auditors.push(defaultAuditors[i])
					}
				}

				console.log('check auditoros auditors', JSON.stringify(this.vacationApplyForm.auditors))

				// 请假小时数
				let hours = 0
				let diff = 0
				for (let i = 0; i != this.qingjiaDetail.length; i++) {
					let detail = this.qingjiaDetail[i]
					if (moment(detail.start).isAfter(moment(detail.end))) continue
					diff += (moment(detail.end).valueOf() - moment(detail.start).valueOf())
				}

				hours = Math.ceil(diff / 1000 / 60 / 60)

				// 是否为科长
				let isKezhang = this.userInfo.uid == this.lingdao.zhijie_lingdao
				// 是否出盐城
				let outYancheng = this.vacationApplyForm.outYancheng == '是'
				if(hours >= 8 || isKezhang ){
					this.addAuditor({uid: this.lingdao.fenguan_lingdao, name: this.lingdao.fenguan_lingdao_name, positionName: this.lingdao.fenguan_lingdao_position_name})
				}

				if(outYancheng || hours >= 8 || (hours > 0 && isKezhang)){
					this.addAuditor({uid: this.lingdao.zhuyao_lingdao, name: this.lingdao.zhuyao_lingdao_name, positionName: this.lingdao.zhuyao_lingdao_position_name})
				}

				this.$forceUpdate()
			},
			async clickApply() {
				console.log(this.vacationApplyForm)

				if (this.vacationApplyForm.startDate == '') {
					return uni.showToast({
						title: '请选择开始时间'
					})
				}

				if (this.vacationApplyForm.endDate == '') {
					return uni.showToast({
						title: '请选择结束时间'
					})
				}

				let diffDays = moment(this.vacationApplyForm.endDate).diff(moment(this.vacationApplyForm.startDate), 'hour')
				if (diffDays <= 0) return uni.showToast({
					title: '结束时间应该大于开始时间',
					icon: 'none'
				})

				if (this.vacationApplyForm.reason == '') {
					return uni.showToast({
						title: '请输入请假原因'
					})
				}

				// 请假小时数
				let hours = 0
				let diff = 0
				for (let i = 0; i != this.qingjiaDetail.length; i++) {
					let detail = this.qingjiaDetail[i]
					if (moment(detail.start).isAfter(moment(detail.end))) continue
					diff += (moment(detail.end).valueOf() - moment(detail.start).valueOf())
				}

				hours = Math.ceil(diff / 1000 / 60 / 60)

				if (hours <= 0) return uni.showToast({
					title: '请假时间错误',
					icon: 'none'
				})

				let auditors = []
				for (let i = 0; i != this.vacationApplyForm.auditors.length; i++) {
					auditors.push({uid: this.vacationApplyForm.auditors[i].uid, stepName: this.vacationApplyForm.auditors[i].stepName || this.vacationApplyForm.auditors[i].positionName})
				}

				try {
					await websock.vacationApply({
						leixing: this.vacationApplyForm.leixing,
						startDate: this.vacationApplyForm.startDate,
						endDate: this.vacationApplyForm.endDate,
						days: hours,
						outYancheng: this.vacationApplyForm.outYancheng,
						reason: this.vacationApplyForm.reason,
						attaches: this.vacationApplyForm.attaches || [],
						auditors,
						detail: this.qingjiaDetail,
						pics: this.vacationApplyForm.pics || []
					})
					uni.showToast({
						title: '提交成功'
					})
					this.vacationApplyForm = {
						leixing: '事假',
						startDate: '',
						endDate: '',
						days: 0,
						outYancheng: '否',
						reason: '',
						auditors: [],
						attaches: [],
						pics: []
					}

					this.currentIndex = 1

					this.getNewestRecord()
				} catch (err) {
					uni.showToast({
						title: err.message
					})
				}
			},

			// 查看详情
			seeDetail(idx) {
				uni.navigateTo({
					url: `/pages/task/qingjiaApplyDetail?id=${this.applyRecord[idx].id}`
				})
			}
		}
	}
</script>

<style>
	@import '../common/common.css';
</style>
